/*
SharpContent
Copyright (c) 2002-2009, State of Montana

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

   1. Redistributions of source code must retain the above copyright notice,
      this list of conditions and the following disclaimer.
   2. Redistributions in binary form must reproduce the above copyright notice,
      this list of conditions and the following disclaimer in the documentation
      and/or other materials provided with the distribution.
   3. Neither the State of Montana nor the names of contributors may be used to endorse
      or promote products derived from this software without specific prior
      written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
DAMAGE.
*/


(function() {
	var window = this, mc = window.mc = function() { };

	REPRESENTATIONS = { json: "json", xml: "xml" };

	mc.getResource = function(url, version, callback) {
		// TODO: Don't append ?nocache when there's already a query parameter
		if (url.indexOf('?ver') < 0)
			url += '?nocache';
		var req = new Request({
			'url': url, // Parameter has no server-side function. Simply prevents browser from holding on to the resource.
			'headers': {'Translate': 'f'},
			'onSuccess': function(responseText) {
				callback(responseText);
			}
		}).get();
	}
	
	mc.deleteItem = function(uri, successCallback) {
		var req = new Request({
			'method': 'delete',
			'url': uri.toString(),
			'emulation': false,
			'onSuccess': function() {
				successCallback();
			}
		});
		req.send();
	};
	
	mc.put = function(url, data, successCallback) {
		var req = new Request({
			'method': 'put',
			'emulation': false,
			'url': url,
			'data': data
		});
		
		req.setHeader('Content-Type', 'text/html');
		
		if (successCallback) {
			req.onSuccess = function(text, xml){
				successCallback(url, xml, this.getHeader('Location'));
			};
		}
			
		req.send();
	}

	mc.options = function(url, callback) {
		var req = new Request({
			method: 'options',
			url: url,
			onSuccess: function(text, xml) {
				callback(text);
			}
		}).send();
	}

	mc.head = function(url, callback) {
		//var results = $.head(url, null, function() { callback(results) });
		var req = new Request({
			method: 'head',
			url: url,
			onSuccess: function(text, xml) {
				callback(text);
			}
		}).send();
	}

	mc.search = function(url, searchTerm, callback) {
		// Just going to search item name until we have a clearer spec and 
		// fix the Search stuff (no partial matches and no operators)
		// TODO: Get clearer spec. Fix search code.
		var query,
			req = new Request({
				'method': 'search',
				'emulation': false,
				'url': url,
				'onSuccess': function(text, xml) {
					callback(xml);
				}
			});
		
		query = '<?xml version="1.0"?>\n<D:searchrequest xmlns:D="DAV:" xmlns:mc="uri://MetaCollection/v2">\n';
		query += '<D:prop><mc:name>' + searchTerm + '</mc:name></D:prop>';
		query += '<D:include><mc:name/><D:displayname/><mc:mimetype/><mc:resourceprovider/><mc:version/><mc:published/></D:include>';
		query += '</D:searchrequest>';
		req.send(query);
	}
	
	// Cross-browser XML support in Javascript is lacking... We'll build strings in the WebDAV methods.
	mc.propfind = function(url, callback, load, properties, failureCallback, sync) {
		var requestData = '';
		requestData += '<?xml version="1.0"?>\n<D:propfind xmlns:D="DAV:" xmlns:mc="uri://MetaCollection/v2">\n';
		if (properties) {
			requestData += '\n<D:prop>';
			properties.each(function(prop) {
				requestData += '<' + prop + '/>\n';
			});
			requestData += '</D:prop>\n';
		} else {
			requestData += '<D:allprop/>\n';
		}
		requestData += '</D:propfind>';

		var req = new Request({
			'method': 'propfind',
			'emulation': false,
			'url': url,
			'async': sync ? false : true,
			'onFailure': function(xhr) { 
				if (failureCallback)
					failureCallback(xhr);
			},
			'onSuccess': function(text, xml) {
				callback(xml);
			}
		}).send(requestData);
	}
	
	mc.proppatch = function(url, callback, set, remove, mcsNS, setXML, removeXML, alertResponse) {
		// Set/remove are hashes where the keys are tag names and the value is an
		// array of key/value pairs. these pairs are of the form [attribute, value].
		// there is one special key called innerText which is the text inside the
		// opening and closing tags.
		var makePatchSet = function(attributes, tagName) {
			// TODO: Simplify this method if we're never going to use more than innerText...
			var innerTextValue = null;
			var setString = '<' + tagName; 
			if (attributes) {
				attributes.each(function(attribute) {
					if (attribute[0] != 'innerText') {  
						setString += ' ' + attribute[0] + '="' + attribute[1] + '"'; 
					} else {
						innerTextValue = attribute[1];
					}
				});
			}
			setString += '>';
			if (innerTextValue)
				setString += innerTextValue;
			setString += '</' + tagName + '>\n';
			return setString;
		};
		 
		if (set)
			var setElements = set.map(makePatchSet);
		if (remove)
			var removeElements = remove.map(makePatchSet);
		
		var requestData = '<?xml version="1.0"?>\n<D:propertyupdate xmlns:D="DAV:" xmlns:mc="uri://MetaCollection/v2" ';
		if (mcsNS)
			requestData +=  'xmlns:mcs="' + mcsNS + '"';
		requestData += '>\n';
		
		// TODO: When properties are tracked and set smartly set/removeXML blocks will may not be able to be coupled to set/removeElements.
		// TODO: Whole shebang needs refactoring, really.
		requestData += '<D:set>\n';
		requestData += '<D:prop>\n';
		if (setElements) {
			setElements.each(function(element) {
				requestData += element;
			});
		}
		if (setXML) {
			requestData += '<mc:relationships>' + setXML + '</mc:relationships>';
		}
		requestData += '</D:prop>\n';
		requestData += '</D:set>\n';
		
		requestData += '<D:remove>\n';
		requestData += '<D:prop>';
		if (removeElements) {
			removeElements.each(function(element) {
				requestData += element;
			});
		}
		if (removeXML) {
			requestData += '<mc:relationships>' + removeXML + '</mc:relationships>';
		}
		requestData += '</D:prop>\n';
		requestData += '</D:remove>\n';
		requestData += '</D:propertyupdate>\n';

		var req = new Request({
			'method': 'proppatch',
			'emulation': false,
			'url': url,
			'onSuccess': function(text, xml) {
				if(callback) {
					callback(xml);
				}
			}
		}).send(requestData);
	}
	
	mc.reportTypes = new Hash({
		'version': '<?xml version="1.0" encoding="utf-8" ?><D:version-tree xmlns:D="DAV:" xmlns:mc="uri://MetaCollection/v2"><D:prop><D:version-name/><D:creator-displayname/><D:predecessor-set/><mc:version-date/><mc:published/><mc:id/></D:prop></D:version-tree>',
		'resource-providers': '<?xml version="1.0" encoding="utf-8" ?><mc:Resource-Providers xmlns:mc="uri://MetaCollection/v2" />',
		'specification-details': '<?xml version="1.0" encoding="utf-8" ?><mc:specificationdetails  xmlns:mc="uri://MetaCollection/v2" id="'
	});
	
	mc.report = function (url, type, callback, sync, specificationDetailsArg) {
		if (type && mc.reportTypes[type]) {
			var requestBody = type == 'specification-details' ? mc.reportTypes[type] + specificationDetailsArg + '" />' : mc.reportTypes[type],
			uri = new URI(url), 
			req = new Request({
				'method': Browser.Engine.trident ? 'propfind' : 'report',
				'emulation': false,
				'async': sync ? false : true,
				'url': uri.setData({
							'nocache': 'true'
						}, true).toString(),
				'onSuccess': function(text, xml) {
					callback(xml);
				}
			});
			if (Browser.Engine.trident) {
				req.setHeader('IEISPOOP', 'REPORT');
			}

			req.send(requestBody);
		}
	}
})();
